package com.gohi.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.LogFactory;

public class RequestFilter implements Filter {

	private static final org.apache.commons.logging.Log Log = LogFactory.getLog(RequestFilter.class);

	private String characterEncoding = "UTF-8";
	private boolean noCache = false;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain filterChain) throws ServletException, IOException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		try {
			request.setCharacterEncoding(this.characterEncoding);
		} catch (UnsupportedEncodingException ex) {
			Log.warn("不支持编码：" + this.characterEncoding);
		}

		response.setContentType("text/html;charset=" + this.characterEncoding);

		if (this.noCache) {
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Cache-Control", "no-cache,must-revalidate");
			response.setDateHeader("Expires", 0L);
		}
		filterChain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String encoding = config.getInitParameter("character-encoding");
		String strNocache = config.getInitParameter("no-cache");
		if (encoding != null) {
			this.characterEncoding = encoding;
		}
		this.noCache = (("yes".equalsIgnoreCase(strNocache)) || ("true".equalsIgnoreCase(strNocache)));
	}

}
